package com.pn.service.impl;

import com.pn.entity.Result;
import com.pn.entity.Role;
import com.pn.mapper.RoleAuthMapper;
import com.pn.mapper.RoleMapper;
import com.pn.page.Page;
import com.pn.service.RoleService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

// 2)指定缓存的名称(数据保存到redis中的键的前缀，一般值给标注@CacheConfig注解的类的全路径)
@CacheConfig(cacheNames = "com.pn.service.impl.RoleServiceImpl")
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleAuthMapper roleAuthMapper;

    // 3)查询方法上标注的@Cacheable指定缓存的键
    @Cacheable(key = "'all:role'")
    @Override
    public List<Role> queryAllRole() {

        return roleMapper.findAllRole();
    }

    @Override
    public List<Role> queryUserRoleByUid(Integer userId) {
        return roleMapper.findUserRoleByUid(userId);
    }

    @Override
    public Page queryRoleByPage(Page page, Role role) {

        // 查询角色
        List<Role> roleList = roleMapper.findRoleByPage(page, role);

        // 查询总条数
        int roleRowCount = roleMapper.findRoleRowCount(role);

        page.setResultList(roleList);
        page.setTotalNum(roleRowCount);

        return page;
    }

    @CacheEvict(key = "'all:role'")
    @Override
    public Result addRole(Role role) {

        // 查询将要添加的角色在表中是否存在
        Role info = roleMapper.findRoleByNameOrCode(role.getRoleName(), role.getRoleCode());
        if (info != null) {
            return Result.err(Result.CODE_ERR_BUSINESS, "角色已存在！");
        }

        int result = roleMapper.insertRole(role);
        if (result > 0) {
            return Result.ok("添加角色成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加角色失败！");
    }

    @CacheEvict(key = "'all:role'")
    @Override
    public Result setRoleDescByRid(Role role) {

        int result = roleMapper.updateRoleDescByRid(role);
        if (result > 0) {
            return Result.ok("角色描述修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "角色描述修改失败！");
    }

    @CacheEvict(key = "'all:role'")
    @Override
    public Result removeRoleByRid(Integer roleId) {

        int result = roleMapper.deleteRoleByRid(roleId);

        if (result > 0) {
            // 删除角色对应权限
            roleAuthMapper.deleteRoleAuthByRid(roleId);
            return Result.ok("删除角色成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "删除角色失败！");
    }

    @CacheEvict(key = "'all:role'")
    @Override
    public Result setRoleStateByRid(Role role) {
        int result = roleMapper.updateRoleStateByRid(role);
        if (result > 0) {
            return Result.ok("修改角色状态成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改角色状态失败！");
    }
}